#include "waveform.h"
typedef QVector<double> DoubleVector;
/**
  Класс, рисующий WaveForm

 * @brief WaveForm::WaveForm
 * @param parent
 */
WaveForm::WaveForm(QString fileName) :
    QCustomPlot()
{
    currentPos = 0;

    this->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);

    //видимая область
    this->xAxis->setRange(0, 300);
    this->yAxis->setRange(-1, 1);
    this->axisRect()->setupFullAxesBox();
    this->xAxis->setLabel("Seconds");

    this->axisRect()->setRangeDrag(this->xAxis->orientation());
    this->axisRect()->setRangeZoom(this->xAxis->orientation());

    connect(this->xAxis, SIGNAL(rangeChanged(QCPRange)), this->xAxis2, SLOT(setRange(QCPRange)));
    qRegisterMetaType<DoubleVector>("QVector<double>");
    thread = new WaveFormThread(fileName);
    connect(thread, SIGNAL(leftData(QVector<double>,QVector<double>)), this, SLOT(getData(QVector<double>,QVector<double>)));
    connect(thread, SIGNAL(rightData(QVector<double>,QVector<double>)), this, SLOT(getData(QVector<double>,QVector<double>)));
    connect(thread, SIGNAL(addSlider()), this, SLOT(addSlider()));
    connect(thread, SIGNAL(clear()), this, SLOT(removeAllGraphs()));
    thread->start();
}

WaveForm::~WaveForm()
{
    thread->disconnect();
    if (!thread->isFinished())
        thread->quit();
    if (thread != NULL) delete thread;
}

void WaveForm::addFX(DWORD type, const void* params)
{
    thread->addFX(type, params);
}

void WaveForm::delEffects()
{
    thread->delEffects();
}

void WaveForm::getData(QVector<double> x, QVector<double> y)
{
    addNewGraph(x, y);
}

void WaveForm::addSlider()
{
    addSlider(currentPos);
}

void WaveForm::addNewGraph(QVector<double> dataX, QVector<double> dataY)
{
    this->addGraph();
    this->graph()->setData(dataX, dataY);
    this->graph()->setLineStyle((QCPGraph::LineStyle)(4));
    QPen graphPen;
    graphPen.setColor(QColor(188, 5, 5));
    graphPen.setWidthF(1);
    this->graph()->setPen(graphPen);
    this->replot();
}

void WaveForm::addSlider(double cur)
{
    QVector<double> x(2), y(2);
    x[0] = cur;
    y[0] = -1;

    x[1] = cur;
    y[1] = 1;

    this->addGraph();
    this->graph()->setData(x, y);
    this->graph()->setLineStyle((QCPGraph::LineStyle)(4));
    QPen graphPen;
    graphPen.setColor(QColor(255, 145, 0));
    graphPen.setWidthF(2);
    this->graph()->setPen(graphPen);
    this->replot();
}

void WaveForm::moveSlider(double cur, double max)
{
    if (this->graphCount() < 2) return;
    QVector<double> x(2), y(2);
    x[0] = cur;
    y[0] = -1;

    x[1] = cur;
    y[1] = 1;
    currentPos = cur;

    this->graph()->setData(x, y);
    this->replot();
}

void WaveForm::removeAllGraphs()
{
  this->clearGraphs();
  this->replot();
}
